//
//  KINGComposeViewController.swift
//  肉荣微博
//
//  Created by king on 15/8/5.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit
import SVProgressHUD

private let kStatusMaxLength = 9

class KINGComposeViewController: UIViewController {
    //懒加载图片选择器
    private lazy var photoPickerVc = KINGPhotoSelectorController()
    //懒加载一个表情控制器
    private lazy var emoticonVC: KINGEmoticonController = KINGEmoticonController { [weak self] (emoticon) -> () in
        //将选择的图片添加到textView中
        self?.textView.insertEmoticon(emoticon)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.orangeColor()
        // 添加子控件，按时图层次添加
        view.addSubview(textView)
        view.addSubview(photoPickerVc.view)
        view.addSubview(toolBar)
        
        //添加自控制器
        addChildViewController(photoPickerVc)
        
        //配置子控件
        prepareNav()
        prepareToolBar()
        prepareTextView()
        preparePhotoPickerVc()
        prepareLengthLabel()
        //添加监听者
        addKeyBoardOberserver()
    }
    //开发细节、在点击弹出的时候，准备好键盘
    override func viewDidAppear(animated: Bool) {
        textView.becomeFirstResponder()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    //toolBar底部约束
    private var toolBarCons:NSLayoutConstraint?
    //准备photoPickerVc
    private func preparePhotoPickerVc() {
        //自动布局
        var s = UIScreen.mainScreen().bounds.size
        s.height = s.height * 0.6
        
        photoPickerVc.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: s)
    }
    //MARK : - 发送微博
    func sendStatus() {
        let text = textView.emoticonText
        if text.characters.count > kStatusMaxLength {
            SVProgressHUD.showInfoWithStatus("输入的文本太长", maskType: SVProgressHUDMaskType.Gradient)
            return
        }
        //如果用户没有选择照片，image为nil
        let image = photoPickerVc.photos.last
        KINGNetworkTools.sharedTools.sendStaties(text, image:image) { (result, error) -> () in
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力", maskType: SVProgressHUDMaskType.Gradient)
                return
            }
            self.closeComposeController()
        }
        print("发送微博")
    }
    //准备控制器头部
    private func prepareNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "closeComposeController")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView()
        let textLabel:UILabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15.0)
        textLabel.text = "发布微博"
        textLabel.sizeToFit()
        let nameLable:UILabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 13.0)
        nameLable.text = KINGUserAccount.userAccount?.name ?? "你是谁"
        textLabel.sizeToFit()
        
        titleView.addSubview(textLabel)
        titleView.addSubview(nameLable)
        
        nameLable.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        textLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        navigationItem.titleView = titleView
    }
    //准备toolBar
    private func prepareToolBar() {
        let nameArr = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items:[UIBarButtonItem] = [UIBarButtonItem]()
        for name in nameArr {
            //设置扩展类之后，只需要这一句话
            items.append(UIBarButtonItem(imageName: name["imageName"]!, target: self, action: name["action"]))
            //添加弹簧按钮
            let flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            items.append(flexible)
        }
        items.removeLast()
        toolBar.items = items
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        //取出toolBar的底部约束
        toolBarCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
    }
    //准备textView
    private func prepareTextView() {
        //textView.text = "老牛吃嫩草"
        //是否留出64的间距
        print(automaticallyAdjustsScrollViewInsets)
        //textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil)
        
        //添加占位标签
        placeholderLabel.text = "分享新鲜事..."
        placeholderLabel.sizeToFit()
        textView.addSubview(placeholderLabel)
        placeholderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
    }
    private func prepareLengthLabel() {
        view.addSubview(lengthLabel)
        lengthLabel.text = String(kStatusMaxLength)
        lengthLabel.sizeToFit()
        //设置布局, 这里的偏移，一定要是-8
        lengthLabel.ff_AlignInner(type: ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -8, y: -8))
    }
    //MARK: - 表情按钮点击事件
    func inputEmoticon() {
//        print("表情按钮被点了")
        //取消注册的监听者、这样可以在切换键盘的时候toolbar不会变动
        removeKeyBoardOberserver()
        //关闭键盘
        textView.resignFirstResponder()
        //切换键盘
        textView.inputView = (textView.inputView == nil) ? emoticonVC.view : nil
        //添加监听者，在下一次激活的时候，直接让toolbar到更改完成的位置
        addKeyBoardOberserver()
        //激活键盘
        textView.becomeFirstResponder()
    }
    //关闭控制器
    func closeComposeController() {
        //关闭控制器的时候，先关闭键盘
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    deinit {
        removeKeyBoardOberserver()
    }
    //注册通知，当前盘变的话时候，让toolBar也跟着改动
    private func addKeyBoardOberserver() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    private func removeKeyBoardOberserver() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //点击、通知、等事件都不能声明为私有的 因为是由运行循环调用
    func keyboardChange(n:NSNotification) {
        print(n)
        let rect = n.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue
        toolBarCons?.constant = -(UIScreen.mainScreen().bounds.height - rect.origin.y)
        UIView.animateWithDuration(0.25) { () -> Void in
            //通知系统强制布局
            self.view.layoutIfNeeded()
        }
    }
    //懒加载控件
    //键盘工具栏
    private lazy var toolBar = UIToolbar()
    //文本视图
    private lazy var textView:UITextView = {
        let tv = UITextView()
        //tv.text = "分享新鲜事"
        tv.font = UIFont.systemFontOfSize(18)
        //设置textView的拖拽效果，保证内容比视图小的时候，也可以滚动
        //tv.alwaysBounceHorizontal = true
        tv.alwaysBounceVertical = true
        //设置开始退拽的时候，让键盘收起来
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //设置代理
        tv.delegate = self
        return tv
    }()
    //占位标签
    private lazy var placeholderLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 18)
    //长度提示标签
    private lazy var lengthLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)
}

extension KINGComposeViewController: UITextViewDelegate{
    //如果输入的是字符串或者emoji或者是图片符号，不会调用代理方法
    func textViewDidChange(textView: UITextView) {
        //当textView中有内容，就隐藏提示信息，并且让发布按钮可以点击
        placeholderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        //计算还能输入多少个字符
        let count = kStatusMaxLength - textView.emoticonText.characters.count
        lengthLabel.text = String(count)
        if count < 0 {
            lengthLabel.textColor = UIColor.redColor()
        }
        
    }
}
